package com.dk.shiro;

import com.dk.pojo.CarUser;
import com.dk.service.CarUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

//自定义认证的类,授权的类
public class LoginUserRealm extends AuthorizingRealm {
    @Autowired
    private CarUserService userService;

    //授权的方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("shiro的授权方法");

        //授权
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        return authorizationInfo;
    }

    //认证方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("shiro的认证方法");

        //1.账号是否存在
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        CarUser user = userService.getInfoByUserName(token.getUsername());
        //账号不存在
        if (user == null){
            return null;
        }

        //判断密码,如果正确成功,错误失败
        return new SimpleAuthenticationInfo(user,user.getPassword(), ByteSource.Util.bytes(user.getSalt()),"");
    }
}
